import React, { useState } from 'react'
import { AutoComplete, message } from 'antd'
import _ from 'loadsh'
import PropTypes from 'prop-types'
import { awaitWrap } from '@js/tool'
import { getInfoListByName } from '../ajax/agentAjax'
const { Option } = AutoComplete

// 改变名称
async function changeName (name, type, setLoading, setInfoList) {
  setInfoList([])
  if (name) {
    setLoading(true)
    const [e, data] = await awaitWrap(getInfoListByName(name, type, setLoading, setInfoList))
    setLoading(false)
    if (e) {
      return message.warning(e.message, 2)
    }
    setInfoList(data)
  }
}

const searchHandle = _.debounce(changeName, 600) // 缓动

// 选择当事人信息
async function selectPersonInfo (formRef, data) {
  const c = formRef.current
  const keys = Object.keys(data)
  const map = {}
  keys.forEach(key => {
    map[key] = data[key] || ''
  })
  delete map.id
  c.setFieldsValue(map)
}

function Main ({ name, formRef, type, value, onChange }) {
  const [loading, setLoading] = useState(false)
  const [infoList, setInfoList] = useState([])
  const notice = <div>{loading ? '检索中' : '无匹配数据'}</div>
  return (
    <AutoComplete value={value} placeholder={`请输入${name}`} onSearch={v => searchHandle(v, type, setLoading, setInfoList)} onChange={onChange} notFoundContent={notice}>
      {infoList.map((li, i) => {
        return (
          <Option key={i} value={li.name}>
            <div onClick={() => selectPersonInfo(formRef, li)}>{`${li.name}（证件号：${li.license || '无'}）`}</div>
          </Option>
        )
      })}
    </AutoComplete>
  )
}

Main.propTypes = {
  formRef: PropTypes.object,
  type: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func
}

Main.defaultProps = {
  formRef: null,
  type: '',
  value: '',
  onChange: () => {}
}

export default Main
